<template>
	<view class="container" :style="{width:windowWidth+'px',height:windowHeight+'px'}">
		<cu-custom :bgLiner="true">
			<block slot="content">签到</block>
		</cu-custom>
		<view class="address_con">
			<view class="box">
				<map style="width: 100%; height: 300px;" :latitude="latitude" :longitude="longitude" :markers="covers"
					:circles="circles">
				</map>
			</view>
			<view class="address_1">电子围栏：<text class="text">{{info.address}}{{kilometre}}米内</text></view>
			<view class="address_2 flex flex-wrap justify-start align-center ">
				<image src="/static/img/local-gray.png"
					style="margin-right: 20rpx;min-width: 25rpx;width: 25rpx;height: 30rpx;"></image>
				<text>{{sign_in_address}}</text>
			</view>
			<view class="remark">{{distance > kilometre?'您不在打卡范围':'您已在打卡范围'}}</view>
		</view>
		<view class="date_con">
			<view class="time">{{date}}</view>
			<view class="remark">拍照</view>
			<view class="upload">
				<!-- <view class="example-body">
               				<uni-file-picker
                            v-model="imageValue"
                            file-mediatype="image"
                             :limit="1"
                             mode="grid"
                             file-extname="png,jpg"
                             @select="fileSelect"
                              @fail="fileFail" 
                              @success="fileSuccess"
                               limit="3">
                               </uni-file-picker>
               </view> -->
				<view class="position-rel m-r-10" v-show="imageValue">
					<image :src="imageValue" class="add-s" @click="preImg()"></image>
					<image src="/static/img/del-gray.png" class="del-gray" @click="delImg"></image>
				</view>
				<view class="" v-show="!imageValue">
					<image src="/static/img/add-s.png" class="add-s" @click="upImg"></image>
				</view>
			</view>
		</view>
		<view @click="signInHadle" class="footer">
			<view class="box">
				<view class="name">签到打卡</view>
				<view class="num">{{nowDate}}</view>
			</view>
		</view>
		<uni-popup ref="popup" type="center" :animation="false">
			<view class="popup_content">
				<view class="image_success">
					<image style="width: 200rpx;height: 200rpx;" src="/static/img/success.png"></image>
				</view>
				<view class="name">签到成功</view>
				<view class="date">签到时间：{{signInTime}}</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	let timer;
	import {
		parseTime
	} from '@/common/date.js';
	export default {
		data() {
			return {
				windowHeight: 650,
				windowWidth: 375,
				date: '',
				nowDate: '',
				imageValue: '',
				sign_in_address: '',
				timer: null,
				signInTime: '',
				longitude: '106.516012',
				latitude: '29.51036',
				covers: [{
						id: 1,
						longitude: '106.516012',
						latitude: '29.51036',
						iconPath: '/static/img/local-business.png',
						width: 32,
						height: 41
					},
					{
						id: 2,
						longitude: '106.517013',
						latitude: '29.51037',
						iconPath: '/static/img/local-mine.png',
						width: 32,
						height: 41,
						callout: null
					},
				],
				callout: {
					bgColor: '#10c1b7',
					content: '已进入打卡范围',
					color: '#ffffff',
					fontSize: 12,
					padding: 6,
					borderRadius: 5,
					display: 'ALWAYS'
				},
				circles: [{
					longitude: '106.516013',
					latitude: '29.51037',
					color: '#91d4e444', // 33表示20%透明度(十六进制)
					fillColor: '#91d4e444', // 22表示13%透明度
					radius: 300, // 1000米=1公里
					strokeWidth: 2
				}],
				clients_id: 0,
				id: 0,
				info: {},
				kilometre: 100,
				distance: 100,
				locationUpdateTimer: null,
				longitudes: '106.519023',
				latitudes: '29.51537',
			}
		},
		onUnload() {
			clearInterval(timer);
			uni.stopLocationUpdate();
		},
		onLoad(option) {
			if (option.id) {
				this.id = option.id;
			}
			if (option.clients_id) {
				this.clients_id = option.clients_id;
				this.getInfo();
			}

			this.windowHeight = uni.getSystemInfoSync().windowHeight;
			this.windowWidth = uni.getSystemInfoSync().windowWidth;
			let time = new Date().getTime()
			let date = parseTime(time, '{m}-{d} ' + ' 星期' + '{a}')
			this.date = date

			const _this = this
			clearInterval(timer);
			timer = setInterval(() => {
				_this.nowDate = parseTime(new Date().getTime(), '{h}:{i}:{s}')
			}, 1000)
		},

		methods: {
			fileSelect(file) { // 文件选择
				console.log(file)
			},
			fileFail(file) { // 上传失败
				console.log(file)
			},
			fileSuccess(file) { // 上传成功
				console.log(file)
			},
			getInfo() {
				let data = {

				}
				this.$http('/api/clientDetail/' + this.clients_id, data, 'get').then(res => {
					if (res.code == 200) {
						let datas = res.data;
						this.info = datas.info;
						this.kilometre = datas.kilometre ? parseFloat(datas.kilometre) * 1000 : 100;
						this.circles[0].longitude = this.info.longitude ? this.info.longitude : '';
						this.circles[0].latitude = this.info.latitude ? this.info.latitude : '';
						this.circles[0].radius = this.kilometre;
						this.longitude = this.info.longitude ? this.info.longitude : '';
						this.latitude = this.info.latitude ? this.info.latitude : '';
						this.covers[0].longitude = this.info.longitude ? this.info.longitude : '';
						this.covers[0].latitude = this.info.latitude ? this.info.latitude : '';
						this.getMineLocation();
					}
				})
			},
			getMineLocation() {
				// uni.getLocation({
				// 	type: 'gcj02 ',
				// 	success: (ress) => {
				// 		console.log('当前位置的经度：' + ress.longitude);
				// 		console.log('当前位置的纬度：' + ress.latitude);
				// 		this.covers[1].longitude = ress.longitude ? ress.longitude : '';
				// 		this.covers[1].latitude = ress.latitude ? ress.latitude : '';
				// 		let distance = this.$util.calculateDistance(this.covers[0].latitude, this.covers[0].longitude, this.covers[1].latitude, this.covers[1].longitude);
				// 		this.distance = distance;
				// 		this.covers[1].callout = {};
				// 		if ( this.kilometre > this.distance) {
				// 			this.covers[1].callout = JSON.parse(JSON.stringify(this.callout));
				// 		}

				// 	}
				// });
				// setTimeout(()=>{
				// 	this.covers[1].callout = null;
				// 	this.covers[1].longitude ='106.517013'
				// 	this.covers[1].latitude ='29.51137'
				// 	this.covers[1].callout = JSON.parse(JSON.stringify(this.callout))
				// },1000)
				// setTimeout(()=>{
				// 	this.covers[1].callout = null;
				// 	this.covers[1].longitude ='106.518013'
				// 	this.covers[1].latitude ='29.51237'
				// 	this.covers[1].callout = JSON.parse(JSON.stringify(this.callout))

				// },2000)
				// setTimeout(()=>{
				// 	this.covers[1].callout = null;
				// 	this.covers[1].longitude ='106.519013'
				// 	this.covers[1].latitude ='29.51337'
				// 	this.covers[1].callout = JSON.parse(JSON.stringify(this.callout))

				// },3000)
				// setTimeout(()=>{
				// 	this.covers[1].callout = null;
				// 	this.covers[1].longitude ='106.519023'
				// 	this.covers[1].latitude ='29.51537'
				// 	this.covers[1].callout = JSON.parse(JSON.stringify(this.callout))
				// },4000)
				uni.startLocationUpdate({
					success: () => {
						console.log('开始接收位置')
						uni.onLocationChange((res) => {
							console.log('位置变化:', res)
							// this.covers[1].callout = null;
							this.$set(this.covers[1], 'callout', null);
							clearTimeout(this.locationUpdateTimer);
							this.locationUpdateTimer = setTimeout(() => {
								// this.covers[1].longitude = res.longitude ? res.longitude : '';
								// this.covers[1].latitude = res.latitude ? res.latitude : '';
								this.$set(this.covers[1], 'longitude', res.longitude || '');
								this.$set(this.covers[1], 'latitude', res.latitude || '');
								// const newCovers = [{
								// 		...this.covers[0]
								// 	},
								// 	{
								// 		...this.covers[1],
								// 		longitude: res.longitude || '',
								// 		latitude: res.latitude || '',
								// 		callout: null // 先清除
								// 	}
								// ];
								// this.covers = newCovers;
								let distance = this.$util.calculateDistance(this.covers[0]
									.latitude, this.covers[0].longitude, this
									.covers[1].latitude, this.covers[1].longitude);
								this.distance = distance;
								console.log('变化前=',this.covers)
								if (this.kilometre > this.distance) {
									// this.covers[1].callout = JSON.parse(JSON.stringify(this.callout));
									this.$set(this.covers[1], 'callout', JSON.parse(JSON
										.stringify(this.callout)));
									// if (this.kilometre > this.distance) {
									// 	const newCoversWithCallout = [{
									// 			...this.covers[0]
									// 		},
									// 		{
									// 			...this.covers[1],
									// 			callout: {
									// 				...this.callout,
									// 				id: `callout-${Date.now()}`
									// 			}
									// 		}
									// 	];
									// 	this.covers = newCoversWithCallout;
									// }
									console.log('变化后=',this.covers)
								}
								// this.covers = [{
								// 		...this.covers[0]
								// 	}, // 第一个marker保持不变
								// 	{
								// 		iconPath: '/static/img/local-mine.png',
								// 		width: 32,
								// 		height: 41,
								// 		id: 2, // 确保ID不变
								// 		longitude: res.longitude || '',
								// 		latitude: res.latitude || '',
								// 		callout: this.kilometre > distance ? {
								// 			...this.callout,
								// 			id: `callout-${Date.now()}` // 为callout添加唯一ID
								// 		} : null
								// 	}
								// ];
								this.sign_in_address = res.street ? res.street : '';
							}, 500)
						})
					},
					fail: (err) => {
						console.error('启动位置更新失败:', err)
					}
				})
			},
			upImg() {
				// uni.chooseImage({
				// 	count: 1, //默认9
				// 	sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
				// 	sourceType: ['camera'],
				// 	success: (res) => {
				// 		console.log(res)
						// let file = res.tempFiles[0];
						// this.$util.uploadService(file, (e) => {
						// 	console.log(e)
						// 	this.imageValue = e;
						// })
				// 	}
				// })
				uni.chooseFile({
				  count: 1,
				  type: 'image',
				  sourceType: ['camera'],
				  success :(res)=> {
				    // tempFilePath可以作为img标签的src属性显示图片
				    console.log(res)
					let file = res.tempFiles[0];
					this.$util.uploadService(file, (e) => {
						console.log(e)
						this.imageValue = e;
					})
				  }
				})
			},
			delImg() {
				this.imageValue = '';
			},
			signInHadle() {
				let distance = this.$util.calculateDistance(this.covers[0].latitude, this.covers[0].longitude, this.covers[
					1].latitude, this.covers[1].longitude);
				if (distance > this.kilometre) {
					uni.showToast({
						title: '您不在打卡范围',
						icon: 'none'
					})
					return;
				}
				if (this.imageValue == '') {
					uni.showToast({
						title: '请先拍照',
						icon: 'none'
					})
					return;
				}
				let data = {
					id: this.id,
					longitude: this.longitude,
					latitude: this.latitude,
					sign_in_address: this.sign_in_address,
					sign_in_img: this.imageValue
				}
				this.$http('/api/visitsSignIn', data, 'get').then(res => {
					if (res.code == 200) {
						this.$refs.popup.open()
						let time = new Date().getTime()
						this.signInTime = parseTime(time, '{h}:{i}')
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				})
			},
			preImg() {
				uni.previewImage({
					urls: [this.imageValue],
					current: 0
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	.popup_content {
		text-align: center;
		width: 90%;
		min-width: 550rpx;
		min-height: 600rpx;
		background-color: #fff;
		border-radius: 20rpx;
		padding-top: 100rpx;

		.image_success {}

		.name {
			text-align: center;
			font-size: 40rpx;
			margin: 37rpx 0;
		}

		.date {
			text-align: center;
			font-size: 30rpx;
			color: #999;
		}
	}

	.container {
		.date_con {

			font-size: 30rpx;
			width: 100%;
			padding-left: 78rpx;

			.time {
				margin-bottom: 30rpx;
			}

			.upload {
				margin-top: 30rpx;
				display: flex;

				.add-s {
					width: 160rpx;
					height: 160rpx;
				}

				.del-gray {
					width: 36rpx;
					height: 36rpx;
					position: absolute;
					top: -10rpx;
					right: -10rpx;
					z-index: 2;
				}
			}
		}

		.address_con {
			min-height: 300rpx;
			width: 750rpx;
			font-size: 28rpx;
			border-bottom: 1px solid #eee;
			padding-bottom: 40rpx;
			margin-bottom: 40rpx;

			.box {
				width: 100%;
				background-color: #ccc;
				text-align: center;
				line-height: 300rpx;
				margin-bottom: 20rpx;
			}

			.address_1 {
				padding: 0 32rpx;
				color: #999;
				margin-bottom: 20rpx;
				box-sizing: border-box;

				.text {
					color: #4072F4
				}
			}

			.address_2 {
				box-sizing: border-box;
				padding: 0 32rpx;
				margin-bottom: 20rpx;
			}

			.remark {
				padding-left: 78rpx;
				color: #999;
			}
		}

		.footer {
			margin-top: 50rpx;
			width: 100%;
			padding-bottom: 80rpx;

			.box {
				margin: auto;
				text-align: center;
				width: 260rpx;
				height: 260rpx;
				border-radius: 50%;
				background-image: url("@/static/img/signIn.png");
				background-size: 100% 100%;
				color: #fff;
				padding-top: 80rpx;

				.name {
					font-size: 34rpx;
					margin-bottom: 16rpx;
				}

				.num {
					font-size: 32rpx;
					opacity: 0.8;
				}
			}
		}
	}
</style>